/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package template;

import common.util.HibernateUtil;
import java.awt.HeadlessException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import system.SystemMassages;

/**
 *
 * @author Rabid
 */
public class SERDefaultRegistrationForm {

    static int i = 0;

    public static boolean save(Object... initObject) {
        System.gc();
        i = i + 1;
        Session session = HibernateUtil.getSession();
        Transaction transaction = session.beginTransaction();
        try {
            for (Object object : initObject) {
                session.save(object);
            }
            transaction.commit();
            JOptionPane.showMessageDialog(null, SystemMassages.SAVED_SUCCESS);
            return true;
        } catch (HibernateException | HeadlessException e) {
            transaction.rollback();
            if (i <= 3) {
                save(initObject);
            }
            JOptionPane.showMessageDialog(null, SystemMassages.SAVING_FAIL);
            Logger.getLogger(SERDefaultRegistrationForm.class.getName()).log(Level.SEVERE, null, e);
            return false;
        } finally {
            HibernateUtil.closeSession();
//            SystemVariyable.session.close();
        }
    }

    static ArrayList<Object> view(String hql) {
        System.gc();
        try {
            Session session = HibernateUtil.getSession();
            Transaction transaction = session.beginTransaction();
            Query qry = session.createQuery(hql);
            List list = qry.list();
            transaction.commit();
            return (ArrayList<Object>) list;

        } catch (HibernateException e) {
            Logger.getLogger(SERDefaultRegistrationForm.class.getName()).log(Level.SEVERE, null, e);
            JOptionPane.showMessageDialog(null, SystemMassages.DATA_RETRIVING_FAIL);
            return null;
        } finally {
            HibernateUtil.closeSession();
//            SystemVariyable.session.close();
        }
    }
}
